package com.simtek.simplayer.utils;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class PlayerLinkUtils {
	public static String resolvePath(String httpUrl, String deviceId) {
		URL url = null;
		try {
			url = (new URI(httpUrl)).normalize().toURL();
		} catch (Exception e) {
			return httpUrl;
		}

		url.getHost();
		url.getPort();
		url.getPath();

		Map<String, String[]> query = UrlParse.parseUrlQueryString(url.getQuery());
		query.put("did", new String[] {
				deviceId
		});

		StringBuilder sb = new StringBuilder().append(url.getProtocol()).append("://").append(url.getHost());
		if (url.getPort() > 0) {
			sb.append(":").append(url.getPort());
		}
		if (!StringUtils.isBlank(url.getPath())) {
			sb.append(url.getPath());
		}
		sb.append("?");
		for (String key : query.keySet()) {
			for (String val : query.get(key)) {
				try {
					val = URLEncoder.encode(val, Charsets.UTF_8.name());
				} catch (UnsupportedEncodingException e) {
				}
				sb.append(key).append("=").append(val);
			}
		}

		return sb.toString();
	}
}
